package com.smart.community.property.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步执行器配置类
 * 为物业公司统计服务提供异步处理能力
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * 配置异步执行器
     * 专门用于物业公司统计数据的异步处理
     * 
     * @return 异步执行器
     */
    @Bean("asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：2个线程专门处理统计任务
        executor.setCorePoolSize(2);
        
        // 最大线程数：最多4个线程同时处理
        executor.setMaxPoolSize(4);
        
        // 队列容量：最多等待10个任务
        executor.setQueueCapacity(10);
        
        // 线程名前缀
        executor.setThreadNamePrefix("PropertyStats-");
        
        // 线程空闲时间：60秒后回收空闲线程
        executor.setKeepAliveSeconds(60);
        
        // 拒绝策略：调用者运行策略，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务完成后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间：30秒
        executor.setAwaitTerminationSeconds(30);
        
        // 初始化
        executor.initialize();
        
        return executor;
    }
}
